package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor  implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前请求 试试 controller请求
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 获取token
        String token = request.getHeader("authorization");

        // 判断token 是否为空
        if(ObjectUtil.isEmpty(token)){
            response.setStatus(401);
//            return false;
//            throw  new BaseException(null,"401",null,"认证失败");
            throw  new BaseException("认证失败");
        }
        // 解析token
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(401);
            throw  new BaseException("认证失败");

        }


        if(ObjectUtil.isEmpty(claims)){
            response.setStatus(401);
            throw  new BaseException("认证失败");
        }
        Long userId = claims.get("userId", Long.class);
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
